/*
 * This file is part of jboss-admin-rest
 * Copyright 2009, Christos Vasilakis (cvasilak@gmail.com)
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */

package org.jboss.admin.rest.services;

import org.jboss.admin.rest.domain.DeploymentsContainer;
import org.jboss.admin.rest.domain.deployments.ManagedDeploymentBean;
import org.jboss.admin.rest.domain.deployments.OperationBean;
import org.jboss.admin.rest.exceptions.BadRequestException;
import org.jboss.admin.rest.exceptions.InternalServerErrorException;
import org.jboss.admin.rest.factory.ProfileServiceFactory;
import org.jboss.admin.rest.util.ManagedDeploymentUtils;
import org.jboss.deployers.spi.management.KnownDeploymentTypes;
import org.jboss.deployers.spi.management.ManagementView;
import org.jboss.managed.api.ManagedDeployment;
import org.jboss.profileservice.spi.NoSuchDeploymentException;
import org.jboss.resteasy.annotations.providers.jaxb.Formatted;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
import java.util.HashSet;
import java.util.Set;

@Produces( {"application/xml", "application/json"} )
public class DeploymentResource extends BaseResource {

	@GET
	@Formatted
	public DeploymentsContainer getDeploymentsList() throws InternalServerErrorException {
		return getDeploymentsList(ANY);
	}

	@POST
	@Consumes("multipart/form-data")
	public Response uploadDeployment(@Context HttpServletRequest request) throws BadRequestException, InternalServerErrorException {
		return super.uploadArtifact(request);
	}

	@GET
	@Path("/{type}")
	@Formatted
	public DeploymentsContainer getDeploymentsList(@PathParam("type") String type) throws InternalServerErrorException {
		DeploymentsContainer list = new DeploymentsContainer();

		list.add(getManagedDeployments(type));

		return list;
	}

	@GET
	@Path("/{type}/{name}")
	@Formatted
	public ManagedDeploymentBean getDeployment(@PathParam("type") String type, @PathParam("name") String name) throws BadRequestException, NoSuchDeploymentException, InternalServerErrorException {
		return ManagedDeploymentUtils.getWrappedDeploymentBean(getManagedDeployment(type, name));
	}

	@PUT
	@Path("/{type}/{name}")
	public Response updateDeployment(@PathParam("type") String type, @PathParam("name") String name, OperationBean operation) throws BadRequestException, NoSuchDeploymentException, InternalServerErrorException {
		return super.updateArtifact(getManagedDeployment(type, name).getName(), operation);
	}

	@DELETE
	@Path("/{type}/{name}")
	public Response undeployDeployment(@PathParam("type") String type, @PathParam("name") String name) throws NoSuchDeploymentException, InternalServerErrorException {
		return super.undeployArtifact(getManagedDeployment(type, name).getName());
	}

	private ManagedDeployment getManagedDeployment(String type, String name) throws NoSuchDeploymentException, InternalServerErrorException {
		Set<ManagedDeployment> deployments;

		try {
			deployments = getManagedDeployments(type);
		} catch (Exception e) {
			throw new InternalServerErrorException(e.getMessage(), e);
		}

		ManagedDeployment match = null;

		for (ManagedDeployment deployment: deployments) {
			if (deployment.getSimpleName().equals(name)) {
				match = deployment;
			}
		}

		if (match == null) {
			throw new NoSuchDeploymentException(name);
		}

		return match;
	}

	private Set<ManagedDeployment> getManagedDeployments(String type) throws InternalServerErrorException {
		ManagementView mv = ProfileServiceFactory.getCurrentManagementView();


		Set<ManagedDeployment> deployments = null;

		/* TODO
		 * throw BadRequestException if the deployment type
		 * is Unknown to the system, instead of an empty set
		 */

		try {
            if (type.equals(ANY)) {
                deployments = new HashSet<ManagedDeployment>();

                for (KnownDeploymentTypes t : KnownDeploymentTypes.values()) {
                    deployments.addAll(mv.getDeploymentsForType(t.getType()));
                }
            } else {
                deployments = mv.getDeploymentsForType(type);
            }
        } catch (Exception e) {
            throw new InternalServerErrorException(e.getMessage(), e);
        }

		return deployments;
	}
}
